<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head, Link, useForm, router } from '@inertiajs/vue3';
import { ref, computed } from 'vue';

const props = defineProps({
    user: Object,
    posts: Object,
    joinedBars: Array,
    ownedBars: Array,
    isOwnProfile: Boolean,
    currentUserUsername: String,
});

// 使用响应式变量跟踪关注状态
const isFollowing = ref(props.user.is_following || false);
const followersCount = ref(props.user.followers_count || 0);
const isProcessing = ref(false); // 用于保持"处理中..."状态

const getUserAvatar = (user) => {
    if (user?.avatar) {
        return user.avatar.startsWith('http') ? user.avatar : `/storage/${user.avatar}`;
    }
    return `https://api.dicebear.com/7.x/avataaars/svg?seed=${user?.name || 'user'}`;
};

const getBarAvatar = (bar) => {
    if (bar.avatar) {
        return bar.avatar.startsWith('http') ? bar.avatar : `/storage/${bar.avatar}`;
    }
    return `https://api.dicebear.com/7.x/shapes/svg?seed=${bar.name}`;
};

const formatNumber = (num) => {
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
};

const formatTime = (time) => {
    if (!time) return '';
    const date = new Date(time);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return date.toLocaleDateString('zh-CN');
};

// 关注表单
const followForm = useForm({});

const handleFollow = () => {
    // 设置处理状态为 true
    isProcessing.value = true;
    
    followForm.post(route('users.follow', props.user.username), {
        preserveScroll: true,
        onSuccess: () => {
            // 立即更新状态
            // 切换关注状态
            isFollowing.value = !isFollowing.value;
            // 更新粉丝数
            if (isFollowing.value) {
                followersCount.value = followersCount.value + 1;
            } else {
                followersCount.value = Math.max(followersCount.value - 1, 0);
            }
            // 同时更新 props 以保持同步
            props.user.is_following = isFollowing.value;
            props.user.followers_count = followersCount.value;
            // 处理完成，关闭处理状态
            isProcessing.value = false;
        },
        onError: () => {
            // 如果出错，也要关闭处理状态
            isProcessing.value = false;
        },
    });
};
</script>

<template>
    <Head :title="user.nickname || user.name || '用户主页'" />

    <AuthenticatedLayout>
        <div class="space-y-6">
            <!-- 用户信息卡片 -->
            <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                <div class="px-6">
                    <div class="flex items-start gap-6">
                        <!-- 头像 -->
                        <img
                            :src="getUserAvatar(user)"
                            :alt="user.nickname || user.name"
                            class="w-24 h-24 rounded-full flex-shrink-0"
                        />
                        
                        <!-- 用户信息 -->
                        <div class="flex-1">
                            <div class="flex items-center gap-3 mb-2">
                                <h1 class="text-2xl font-bold">
                                    {{ user.nickname || user.name }}
                                </h1>
                                <span class="inline-flex items-center justify-center rounded-md border border-transparent bg-secondary text-secondary-foreground px-2 py-0.5 text-xs font-medium">
                                    Lv.{{ user.level }}
                                </span>
                                <span v-if="isOwnProfile" class="inline-flex items-center justify-center rounded-md border border-transparent bg-secondary text-secondary-foreground px-2 py-0.5 text-xs font-medium">
                                    我的主页
                                </span>
                            </div>
                            
                            <p v-if="user.signature" class="text-muted-foreground mb-4">{{ user.signature }}</p>
                            
                            <!-- 统计数据 -->
                            <div class="flex gap-6 text-sm">
                                <!-- 粉丝数（所有用户都可点击） -->
                                <Link
                                    :href="route('users.followers', user.username)"
                                    class="cursor-pointer hover:opacity-80 transition-opacity"
                                >
                                    <div class="font-semibold">{{ formatNumber(isOwnProfile ? (user.followers_count || 0) : followersCount) }}</div>
                                    <div class="text-muted-foreground">粉丝</div>
                                </Link>
                                <!-- 关注数（所有用户都可点击） -->
                                <Link
                                    :href="route('users.following', user.username)"
                                    class="cursor-pointer hover:opacity-80 transition-opacity"
                                >
                                    <div class="font-semibold">{{ formatNumber(user.following_count || 0) }}</div>
                                    <div class="text-muted-foreground">关注</div>
                                </Link>
                                <div>
                                    <div class="font-semibold">{{ formatNumber(user.posts_count) }}</div>
                                    <div class="text-muted-foreground">帖子</div>
                                </div>
                                <div>
                                    <div class="font-semibold">{{ formatNumber(user.favorites_count) }}</div>
                                    <div class="text-muted-foreground">收藏</div>
                                </div>
                                <div>
                                    <div class="font-semibold">{{ formatNumber(user.joined_bars_count) }}</div>
                                    <div class="text-muted-foreground">关注的贴吧</div>
                                </div>
                                <div>
                                    <div class="font-semibold">{{ formatNumber(user.owned_bars_count) }}</div>
                                    <div class="text-muted-foreground">创建的贴吧</div>
                                </div>
                            </div>
                            
                            <!-- 操作按钮 -->
                            <div v-if="!isOwnProfile && $page.props.auth?.user" class="mt-4">
                                <form @submit.prevent="handleFollow" class="inline-block">
                                    <button
                                        type="submit"
                                        :disabled="followForm.processing || isProcessing"
                                        class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all h-9 px-4 py-2 shadow-sm"
                                        :class="isFollowing ? 'bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input' : 'bg-primary text-primary-foreground hover:bg-primary/90'"
                                    >
                                        <span v-if="followForm.processing || isProcessing">处理中...</span>
                                        <span v-else>{{ isFollowing ? '已关注' : '关注' }}</span>
                                    </button>
                                </form>
                            </div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div class="flex gap-2 flex-shrink-0">
                            <Link
                                v-if="!isOwnProfile && currentUserUsername"
                                :href="route('users.show', currentUserUsername)"
                                class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all border bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2"
                            >
                                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                </svg>
                                查看我的主页
                            </Link>
                            <Link
                                v-else-if="isOwnProfile"
                                :href="route('profile.show')"
                                class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all border bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2"
                            >
                                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                </svg>
                                编辑资料
                            </Link>
                        </div>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- 左侧主要内容 -->
                <div class="lg:col-span-2 space-y-6">
                    <!-- 发布的帖子 -->
                    <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                        <div class="px-6">
                            <h2 class="text-2xl font-bold mb-4">发布的帖子</h2>
                            
                            <div v-if="posts && posts.data && posts.data.length" class="space-y-4">
                                <Link
                                    v-for="post in posts.data"
                                    :key="post.id"
                                    :href="route('posts.show', post.slug)"
                                    class="block border rounded-lg p-4 hover:bg-accent transition-colors cursor-pointer"
                                >
                                    <div class="flex items-start gap-4">
                                        <div class="flex-1 min-w-0">
                                            <div class="flex items-center gap-2 mb-1">
                                                <Link
                                                    :href="route('bars.show', post.bar?.slug)"
                                                    class="inline-flex items-center justify-center rounded-md border border-transparent bg-secondary text-secondary-foreground px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0"
                                                    @click.stop
                                                >
                                                    {{ post.bar?.name }}
                                                </Link>
                                                <span class="text-sm text-muted-foreground">{{ formatTime(post.created_at) }}</span>
                                            </div>
                                            <h3 class="font-bold text-lg mb-2">
                                                {{ post.title }}
                                            </h3>
                                            <p class="text-muted-foreground line-clamp-2 mb-3">{{ post.content }}</p>
                                            <div class="flex items-center gap-4 text-sm text-muted-foreground">
                                                <span class="flex items-center gap-1">
                                                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                                                    </svg>
                                                    {{ formatNumber(post.like_count) }}
                                                </span>
                                                <span class="flex items-center gap-1">
                                                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                                                    </svg>
                                                    {{ formatNumber(post.reply_count || 0) }}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </Link>
                            </div>
                            <div v-else class="text-center py-12 text-muted-foreground">
                                <p>还没有发布过帖子</p>
                            </div>

                            <!-- 分页 -->
                            <div v-if="posts && posts.links && posts.links.length > 3" class="flex items-center justify-center gap-2 pt-6 border-t mt-4 px-6">
                                <Link
                                    v-for="(link, index) in posts.links"
                                    :key="index"
                                    :href="link.url || '#'"
                                    v-html="link.label"
                                    class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all h-9 px-3 py-2"
                                    :class="{
                                        'bg-primary text-primary-foreground shadow-sm': link.active,
                                        'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground': !link.active && link.url,
                                        'text-muted-foreground cursor-not-allowed opacity-50': !link.url
                                    }"
                                />
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧边栏 -->
                <div class="space-y-6">
                    <!-- 创建的贴吧 -->
                    <div v-if="ownedBars && ownedBars.length" class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                        <div class="px-6">
                            <h3 class="text-lg font-bold mb-4">创建的贴吧</h3>
                            <div class="space-y-3">
                                <Link
                                    v-for="bar in ownedBars"
                                    :key="bar.id"
                                    :href="route('bars.show', bar.slug)"
                                    class="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors"
                                >
                                    <img
                                        :src="getBarAvatar(bar)"
                                        :alt="bar.name"
                                        class="w-12 h-12 rounded-lg flex-shrink-0 object-cover"
                                    />
                                    <div class="flex-1 min-w-0">
                                        <div class="font-semibold truncate">{{ bar.name }}</div>
                                        <div class="text-sm text-muted-foreground">{{ formatNumber(bar.member_count) }} 成员</div>
                                    </div>
                                </Link>
                            </div>
                        </div>
                    </div>

                    <!-- 加入的贴吧 -->
                    <div v-if="joinedBars && joinedBars.length" class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                        <div class="px-6">
                            <h3 class="text-lg font-bold mb-4">关注的贴吧</h3>
                            <div class="space-y-3">
                                <Link
                                    v-for="bar in joinedBars"
                                    :key="bar.id"
                                    :href="route('bars.show', bar.slug)"
                                    class="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors"
                                >
                                    <img
                                        :src="getBarAvatar(bar)"
                                        :alt="bar.name"
                                        class="w-12 h-12 rounded-lg flex-shrink-0 object-cover"
                                    />
                                    <div class="flex-1 min-w-0">
                                        <div class="font-semibold truncate">{{ bar.name }}</div>
                                        <div class="text-sm text-muted-foreground">{{ formatNumber(bar.member_count) }} 成员</div>
                                    </div>
                                </Link>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>

